import {
  ArgumentsHost,
  Catch,
  ExceptionFilter,
  HttpException,
  HttpStatus,
  Logger,
} from '@nestjs/common';
import { codStatus } from '../../config/config';

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse();
    const request = ctx.getRequest();
    let message = exception.message;
    const status =
      exception instanceof HttpException
        ? exception.getStatus()
        : HttpStatus.INTERNAL_SERVER_ERROR;
    if (status === 401) {
      message = '未授权，请登录！';
    }
    // 设置返回的状态码、请求头、发送错误信息
    Logger.error('错误提示', message, status);
    console.log(codStatus[status]);
    Logger.verbose(exception.stack);
    const errorResponse = {
      data: {
        msg: codStatus[status],
      }, // 获取全部的错误信息
      msg: message,
      code: status, // 自定义code
      url: request.originalUrl, // 错误的url地址
    };
    response.status(status);
    response.header('Content-Type', 'application/json; charset=utf-8');
    response.send(errorResponse);
  }
}
